package top.kikt.book.core.handlers

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler

class Biqugse : BaseBookHandler() {

    override val host: String = "www.biqugse.com"

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val name = document.select("#info > h1").text().trim()
        val authorSrc = document.select("#info > p:nth-child(2)").text().trim()
        val author = authorSrc.substring(authorSrc.indexOf("者："))
        val coverImageUrl = document.select("#fmimg > img").attr("src")
        val coverUri = url.toHttpUrl().resolve(coverImageUrl)
        return BookMetaEntity(name, url, url, author, coverUri?.toString())
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val result = ArrayList<ChapterMetaEntity>()
        val dl = document.select("#list > dl")[0]
        val dlChildren = dl.children()
        val dlIndex = dlChildren.indexOfLast { it.tagName() == "dt" }
        val children = dlChildren.subList(dlIndex + 1, dlChildren.count())
        for ((index, child) in children.withIndex()) {
            val a = child.select("a")[0]
            val name = a.text().trim()
            val link = menuUrl.toHttpUrl().resolve(a.attr("href"))
            result.add(
                ChapterMetaEntity(name, index, link.toString(), child)
            )
        }
        return result
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val url = chapterMetaEntity.url
        val doc = url.toHttpUrl().toDocument() ?: return null
        val text = doc.select("#content")[0].wholeText()
        return ChapterEntity(chapterMetaEntity.name, chapterMetaEntity.index, text)
    }
}